package com.fh.controller.information.student;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.service.information.student.StudentService;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.GetPinyin;
import com.fh.util.PageData;
import com.fh.util.Tools;

/**
 * 类名称：NoticeController
 * 创建人：FH
 * 创建时间：2014年12月1日
 * 
 * @version
 */
@Controller
@RequestMapping(value = "/schoolstudent")
public class StudentController extends BaseController {
	@Resource(name = "studentService")
	private StudentService studentService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpSession session, Page page) throws Exception {
		logBefore(logger, "学生列表");
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		try {
			pd = this.getPageData();

			// 检索条件================================
			String search = pd.getString("search");
			if ((null != search) && !"".equals(search)) {
				search = search.trim();
				pd.put("studentpiny", search);
			}
			// 检索条件================================

			pd.put("schoolid", getSessionCompanyid());
			page.setPd(pd);
			List<PageData> List = studentService.list(page);
			if (List.size() > 0) {
				for (int i = 0; i < List.size(); i++) {
					Map<String, Object> map = List.get(i);
					PageData pds = new PageData();
					pds.put("studentid", map.get("id"));
					List<PageData> SClist = studentService.SClistAll(pds);
					StringBuffer sb = new StringBuffer();
					if (SClist.size() > 0) {
						for (PageData rolename : SClist) {
							sb.append(rolename.getString("classname"));
							sb.append(",");
						}
						sb.deleteCharAt(sb.length() - 1);
					}
					map.put("classname", sb);
				}
			}

			mv.setViewName("information/school/student/student_list");
			mv.addObject("List", List);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}

		return mv;
	}

	/**
	 * 
	 * TODO 方法作用：跳转至详细页面
	 * 
	 * @return
	 * @Author: 孙超文
	 * @Date: 2015-7-2 上午9:45:53
	 */
	@RequestMapping(value = "/goFind")
	public ModelAndView goFind() {
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {

			pd = studentService.findById(pd);
			PageData pds = new PageData();
			pds.put("studentid", pd.get("id"));
			List<PageData> SClist = studentService.SClistAll(pds);
			StringBuffer sb = new StringBuffer();
			if (SClist.size() > 0) {
				for (PageData rolename : SClist) {
					sb.append(rolename.getString("classname"));
					sb.append(",");
				}
				sb.deleteCharAt(sb.length() - 1);
			}
			pd.put("classname", sb);
			mv.setViewName("information/school/student/student_from");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 去新增页面
	 */
	@RequestMapping(value = "/goAdd")
	public ModelAndView goAdd() {
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("information/school/student/student_edit");
			mv.addObject("msg", "save");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 去修改页面
	 */
	@RequestMapping(value = "/goEdit")
	public ModelAndView goEdit() {
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {

			pd = studentService.findById(pd);
			PageData pds = new PageData();
			pds.put("studentid", pd.getString("id"));
			List<PageData> SClist = studentService.SClistAll(pds);
			pd.put("classList", JSONArray.fromObject(SClist));
			mv.setViewName("information/school/student/student_edit");
			mv.addObject("msg", "edit");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(PrintWriter out) throws Exception {
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		// 删除学生班级关系
		PageData pdur = new PageData();
		String Studentid = pd.getString("id");
		pdur.put("studentid", Studentid);
		studentService.deleteC(pdur);
		// 添加到班级
		PageData pds = new PageData();
		if (Tools.notEmpty(pd.getString("classid"))) {
			String[] classlist = pd.getString("classid").split(",");
			for (String classid : classlist) {
				pds.put("id", this.get32UUID());
				pds.put("studentid", Studentid);
				pds.put("classid", classid);
				pds.put("createdate", DateUtil.getTime());
				studentService.saveclass(pds);
			}
		}
		pd.put("studentpiny", GetPinyin.getPinYinHeadChar(pd.getString("studentname")));
		pd.put("modifier", getSessionUserid()); // 修改人
		pd.put("modifydate", DateUtil.getTime()); // 修改时间
		studentService.edit(pd);

		mv.addObject("msg", "success");
		mv.setViewName("save_result");
		return mv;
	}

	/**
	 * 保存公司公告
	 */
	@RequestMapping(value = "/save")
	public ModelAndView save(PrintWriter out) throws Exception {
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String Studentid = get32UUID();
		pd.put("id", Studentid);
		// 公司简拼为null，系统设置首字母
		pd.put("studentpiny", GetPinyin.getPinYinHeadChar(pd.getString("studentname")));
		pd.put("schoolid", getSessionCompanyid());
		pd.put("creator", getSessionUserid()); // 新增人
		pd.put("modifier", getSessionUserid()); // 修改人
		pd.put("createdate", DateUtil.getTime()); // 新增时间
		pd.put("modifydate", DateUtil.getTime()); // 修改时间
		// 添加到班级
		PageData pds = new PageData();
		if (Tools.notEmpty(pd.getString("classid"))) {
			String[] classlist = pd.getString("classid").split(",");
			for (String classid : classlist) {
				pds.put("id", this.get32UUID());
				pds.put("studentid", Studentid);
				pds.put("classid", classid);
				pds.put("createdate", DateUtil.getTime());
				studentService.saveclass(pds);
			}
		}
		studentService.save(pd);
		mv.addObject("msg", "success");
		mv.setViewName("save_result");
		return mv;
	}

	/**
	 * 物理删除
	 */
	@RequestMapping(value = "/delete")
	public void delete(PrintWriter out) throws Exception {
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		try {
			pd = this.getPageData();
			studentService.delete(pd);
			out.write("success");
			out.close();
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}

	}

	/* ===========================================导入导出============================== */

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
	}

	/* ===============================权限================================== */
	public Map<String, String> getHC() {
		Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
}
